package com.agents.builder.common.script.impl;

import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.agents.builder.common.script.common.CommonScriptExecutor;
import com.agents.builder.common.script.enums.ScriptLanguage;
import org.noear.liquor.eval.CodeSpec;
import org.noear.liquor.eval.Execable;
import org.noear.liquor.eval.ParamSpec;
import org.noear.liquor.eval.Scripts;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class JavaExecutorImpl  extends CommonScriptExecutor {

    private boolean isCache;
    @Override
    public ScriptLanguage type() {
        return ScriptLanguage.JAVA;
    }

    @Override
    public Object execute(String script, Map<String, Object> params) throws Exception {
        Execable execable = (Execable) compile(script);
        return execable.exec(params);
    }

    @Override
    public Object compile(String script) throws Exception {
        CodeSpec codeSpec = new CodeSpec(convertScript(script))
                .returnType(Object.class)
                .parameters(new ParamSpec("_meta", Map.class)).cached(true);
        return Scripts.compile(codeSpec);
    }



    private String convertScript(String script){
        //替换掉public，private，protected等修饰词
        String script1 = script.replaceAll("public class", "class")
                .replaceAll("private class", "class")
                .replaceAll("protected class", "class");

        //分析出class的具体名称
        String className = ReUtil.getGroup1("class\\s+(\\w+)\\s+implements", script1);

        if (StrUtil.isBlank(className)){
            throw new RuntimeException("cannot find class defined");
        }

        return "com.asiainfo.aiagent.components.script.body.CommonScriptBody;\n" +
                script1 + "\n" +
                StrUtil.format("{} item = new {}();\n", className, className) +
                "if (item instanceof CommonScriptBody){item.body(_meta);return null;}else{return item.body(_meta);}";
    }
}
